package com.tj.jinzao.base;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.constant.UserInfoFieldEnum;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.tj.jinzao.R;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.model.User;
import com.tj.jinzao.utils.StatusBarHeightUtil;
import com.tj.jinzao.widgets.CustomWaitDialog;

import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;


/**
 * Activity基类
 * Created by wjy on 2016/3/8.
 */
public abstract class BaseActivity<T extends BasePresenter> extends AppCompatActivity {

    protected Fragment mFragment;
    protected Toolbar mToolbar;
    protected Menu mMenu;
    protected TextView mCenterTitleView;

    protected T mPresenter;
    //是否支持沉浸式状态栏
    private final static boolean IS_IMMERSIVE_STATUS_BAR;

    static {
        IS_IMMERSIVE_STATUS_BAR = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    }

    private boolean mOpenImmersiveBar = false;//默认关闭沉浸式
    public CustomWaitDialog progressDialog = null;

    public void startProgressDialog(Context context) {
        if (progressDialog == null) {
            progressDialog = new CustomWaitDialog(context);
        }
        progressDialog.show();
    }

    public void stopProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }


    protected enum Title_Align {
        CENTER, LEFT
    }

    private Title_Align mTitle_Direction = Title_Align.CENTER;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //4.4以上支持沉浸式
        if (IS_IMMERSIVE_STATUS_BAR && mOpenImmersiveBar) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        AppExit.getInstance().addActivity(this);
        int layoutRes = getLayoutResource();
        if (layoutRes != 0) setContentView(layoutRes);
        ButterKnife.bind(this);
        mToolbar = findViewById(R.id.toolbar);
        if (mToolbar != null) {
            if (IS_IMMERSIVE_STATUS_BAR && mOpenImmersiveBar) {
                int statusBarHeight = StatusBarHeightUtil.getStatusBarHeight(getBaseContext());
                mToolbar.setPadding(0, statusBarHeight, 0, 0);
            }
            mCenterTitleView = (TextView) findViewById(R.id.toolbar_title);
            setTitleText(getTitle());
            setSupportActionBar(mToolbar);

            if (getLeftButtonResId() != 0) {
                mToolbar.setNavigationIcon(getLeftButtonResId());
            }
        }
        Window window = getWindow();
        if (translucentStatusBar()) {
            // 设置状态栏全透明
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
        }

        mFragment = createFragment();
        if (mFragment != null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_container, mFragment)
                    .commit();
        }
        mPresenter = createPresenter();
        findId();
        initLinstener();
        setupView();
        requsetData();
    }

    public boolean isImmersiveStatusBar() {
        return IS_IMMERSIVE_STATUS_BAR && mOpenImmersiveBar;
    }

    public void setOpenImmersiveBar(boolean open) {
        mOpenImmersiveBar = open;
    }
    /**
     * 子类可以重写决定是否使用透明状态栏
     */
    protected boolean translucentStatusBar() {
        return false;
    }
    public void setStausBar(int color){
        Window window = getWindow();
        // 沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //5.0以上使用原生方法
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(color);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //4.4-5.0使用三方工具类，有些4.4的手机有问题，这里为演示方便，不使用沉浸式
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintColor(color);
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        mMenu = menu;
        getMenuInflater().inflate(R.menu.menu_main, menu);

        int id = getRightButtonResId();
        CharSequence text = getRightButtonText();
        Drawable drawable = getRightButtonDrawable();
        MenuItem menuItem = menu.getItem(1);
        if (text != null || id != 0 || drawable != null) {
            if (text != null) menuItem.setTitle(text);
            if (id != 0) menuItem.setIcon(id);
            if (drawable != null) menuItem.setIcon(drawable);
        } else {
            menuItem.setVisible(false);
        }

        int rightId2 = getRightButton2ResId();
        CharSequence rightText2 = getRightButton2Text();
        Drawable rightDrawable2 = getRightButton2Drawable();
        MenuItem menuItem2 = menu.getItem(0);
        if (rightText2 != null || rightId2 != 0 || rightDrawable2 != null) {
            if (rightText2 != null) menuItem2.setTitle(rightText2);
            if (rightId2 != 0) menuItem2.setIcon(rightId2);
            if (rightDrawable2 != null) menuItem2.setIcon(rightDrawable2);
        } else {
            menuItem2.setVisible(false);
        }
        setupToolBarRight();
        return true;
    }
    public void updateUserInfo(final User user){
        Map<UserInfoFieldEnum, Object> fields = new HashMap<>();
        fields.put(UserInfoFieldEnum.Name,user.getNickname());
        fields.put(UserInfoFieldEnum.AVATAR, Constant.IMAGE_PREFIX+user.getImgurl());
        NIMClient.getService(UserService.class).updateUserInfo(fields)
                .setCallback(new RequestCallbackWrapper<Void>() {
                    @Override
                    public void onResult(int i, Void aVoid, Throwable throwable) {
                    }
                });

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (android.R.id.home == id) {
            clickLeftButton();
            return true;
        }
        if (R.id.action_right == id) {
            clickRightButton();
            return true;
        }
        if (R.id.action_right2 == id) {
            clickRight2Button();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    //设置标题
    protected void setTitleText(CharSequence title) {
        if (mTitle_Direction == Title_Align.CENTER && mCenterTitleView != null) {
            mCenterTitleView.setText(title);
            mToolbar.setTitle("");
        } else {
            mToolbar.setTitle(title);
        }
    }

    protected T createPresenter() {
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) mPresenter.detachView();
    }

    //设置标题位置 See {@link Title_Align}
    protected void setTitleAlign(Title_Align align) {
        mTitle_Direction = align;
    }

    //是否需要fragment
    protected Fragment createFragment() {
        return null;
    }

    //activity初始化view
    protected void setupView() {
    }
    //activity初始化监听
    protected void initLinstener() {
    }
    //初始化id
    protected void findId(){}
    //初始化数据
    protected void requsetData(){}

    protected void setupToolBarRight() {
    }

    //获取布局
    public abstract int getLayoutResource();

    //点击toolbar左按钮
    protected void clickLeftButton() {
        finish();
    }

    //点击toolbar右按钮
    protected void clickRightButton() {
    }

    //点击toolbar右按钮
    protected void clickRight2Button() {
    }

    //设置toolbar右按钮图案
    protected int getRightButtonResId() {
        return 0;
    }

    //设置toolbar右边第二个按钮图案
    protected int getRightButton2ResId() {
        return 0;
    }

    //设置toolbar右按钮文字
    protected CharSequence getRightButtonText() {
        return null;
    }

    //设置toolbar右边第二个按钮文字
    protected CharSequence getRightButton2Text() {
        return null;
    }

    //设置toolbar右边按钮drawable
    protected Drawable getRightButtonDrawable() {
        return null;
    }

    //设置toolbar右边第二个按钮drawable
    protected Drawable getRightButton2Drawable() {
        return null;
    }

    //设置toolbar左按钮图案
    protected int getLeftButtonResId() {
        return 0;
    }
}